<template>
  <div class="app-main-container">
    <div class="app-main-title">排课
      <div class="goback" @click="$router.go(-1)">
        <i class="el-icon-refresh-left" /> 返回上一页
      </div>
    </div>
    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="120px"
      label-suffix="："
    >
      <el-form-item label="课程名称">
        <el-input
          v-model="courseName"
          type="text"
          placeholder="请输入课程名称"
          disabled
          maxlength="20"
          class="w400"
        />
      </el-form-item>
      <el-form-item label="课程类目">
        <el-input
          v-model="courseItem"
          type="text"
          placeholder="请输入课程类目"
          disabled
          maxlength="20"
          class="w400"
        />
      </el-form-item>
      <!-- <el-form-item label="课时编号" prop="classNum">
        <el-input
          v-model="param.classNum"
          type="number"
          placeholder="请输入课时编号"
          maxlength="20"
        />
      </el-form-item> -->
      <el-form-item label="上课教练" prop="teacherId">
        <el-select v-model="param.teacherId" placeholder="请选择上课教练" class="w400">
          <el-option
            v-for="item in jlList"
            :key="item.teacherId"
            :label="item.teacherName"
            :value="item.teacherId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上课地点类型" prop="siteType">
        <el-radio-group v-model="param.siteType ">
          <el-radio label="1">自定义</el-radio>
          <el-radio label="2">选择场次</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="param.siteType == 2">
        <el-button
          type="primary"
          @click="showCc"
        >选择场次</el-button>
      </el-form-item>
      <el-form-item v-if="param.siteType" label="上课日期" prop="classDay">
        <el-date-picker
          v-model="param.classDay"
          class="w400"
          :picker-options="pickerOptions"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
          :disabled="param.siteType != 1"
        />
      </el-form-item>
      <el-form-item v-if="param.siteType" label="上课时间" prop="time">
        <el-time-picker
          v-model="param.time"
          is-range
          value-format="HH:mm"
          format="HH:mm"
          :clearable="false"
          class="w400"
          range-separator="至"
          start-placeholder="开始时刻"
          end-placeholder="结束时刻"
          :disabled="param.siteType != 1"
        />
      </el-form-item>
      <el-form-item v-if="param.siteType" label="上课地点" prop="site">
        <el-input
          v-model="param.site"
          type="text"
          placeholder="请输入上课地点"
          class="w400"
          maxlength="20"
          :disabled="param.siteType != 1"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          v-preventReClick
          type="primary"
          @click="onSubmit()"
        >提交</el-button>
      </el-form-item>
    </el-form>
    <Replacement ref="replacement" @replacementList="replacementBtn" />
  </div>
</template>

<script>
import store from '@/store'
import { addCourseTime, infoCourse, teacherList, detailCourseTime } from '@/api'
import Replacement from '@/components/replacement.vue'
export default {
  name: 'ScheduleCardEdit',
  components: {
    Replacement
  },
  data() {
    var newRule = (rule, value, callback) => {
      console.log(value[0], 7, value[1])
      if (!value[0]) {
        callback(new Error(rule.message || '请选择场区'))
      } else if (!value[1]) {
        callback(new Error(rule.message || '请选择场地'))
      } else {
        callback()
      }
    }
    var newRuleb = (rule, value, callback) => {
      console.log(value[0], 7, value[1])
      if (value[0] === undefined && value[1] === undefined) {
        callback(new Error(rule.message || '请输入课程人数范围'))
      } else if (!/^\+?[1-9][0-9]*$/.test(value[0]) || !/^\+?[1-9][0-9]*$/.test(value[1])) {
        callback(new Error(rule.message || '请输入正确人数'))
      } else if (value[0] < 1) {
        callback(new Error(rule.message || '请输入正确人数范围'))
      } else if (Number(value[0]) > Number(value[1])) {
        callback(new Error(rule.message || '请输入正确人数范围'))
      } else {
        callback()
      }
    }
    return {
      modalDialog: store.getters.dialog,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
        }
      },
      presentTime: new Date(new Date().toLocaleDateString()).getTime(),
      jlList: [],
      venueId: sessionStorage.getItem('venueId'),
      param: {
        venueId: sessionStorage.getItem('venueId')
      },
      rules: {
        classNum: [{ pattern: /^\+?[1-9][0-9]*$/, required: true, message: '请输入正确课时编号', trigger: 'blur' }],
        site: [{ required: true, message: '请输入上课地点', trigger: 'blur' }],
        dd: [{ required: true, validator: newRule, trigger: ['change', 'change'] }],
        teacherId: [{ required: true, message: '请选择授课教练', trigger: 'change' }],
        classDay: [{ required: true, message: '请选择上课日期', trigger: 'change' }],
        time: [{ required: true, message: '请选择上课时间', trigger: 'change' }],
        siteType: [{ required: true, message: '请选择上课地点类型', trigger: 'change' }],
        rs: [{ required: true, validator: newRuleb, trigger: ['change', 'change'] }]
      },
      courseId: '',
      courseName: '',
      courseItem: '',
      edit: false,
      timeId: '',
      activeDate: '',
      areaList: [],
      siteIds: [],
      projectId: '',
      reserveForm: []
    }
  },
  created() {
    this.getTeachList()
  },
  mounted() {
    this.courseId = this.$route.query.courseId
    this.activeDate = this.formatDate(new Date()).value
    this.getDetail()
    if (this.$route.query.timeId) {
      this.edit = true
      this.timeId = this.$route.query.timeId
      this.getCourseTime()
    }
  },
  methods: {
    getCourseTime() {
      detailCourseTime({ param: { timeId: this.timeId }})
        .then(res => {
          this.param = {
            ...res.record,
            time: [res.record.beginTime, res.record.endTime]
          }
        })
    },
    replacementBtn(e) {
      this.siteIds = e.siteIds
      this.reserveForm = e.reserveForm
      const arr = this.reserveForm
      if (arr.length > 0) {
        this.$set(this.param, 'classDay', arr[0].day)
        const ksList = []
        const jsList = []
        const siteList = []
        arr.forEach(e => {
          ksList.push(e.beginTime)
          jsList.push(e.endTime)
          siteList.push(e.name)
        })
        const ks = ksList[0].replace(':', '')
        const js = jsList[0].replace(':', '')
        let ksIndex = 0
        let jsIndex = 0
        ksList.forEach((e, index) => {
          if (ks > e.replace(':', '')) {
            ksIndex = index
          }
        })
        jsList.forEach((e, index) => {
          if (js < e.replace(':', '')) {
            jsIndex = index
          }
        })
        this.$set(this.param, 'time', [ksList[ksIndex], jsList[jsIndex]])
        this.$set(this.param, 'site', Array.from(new Set(siteList)).join(','))
        this.$set(this.param, 'siteId', this.siteIds.join(','))
      }
    },
    showCc() {
      this.activeDate = this.formatDate(new Date()).value
      this.$refs.replacement.showBtn(this.activeDate, this.projectId, [])
    },
    // 获取星期
    calculation(s) {
      return s < 10 ? '0' + s : s
    },
    formatDate(date) {
      const year = date.getFullYear() + '-'
      const month = this.calculation(date.getMonth() + 1) + '-'
      const day = this.calculation(date.getDate())
      const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
      return {
        label: month + day + ' ' + week,
        value: year + month + day,
        old: new Date(date)
      }
    },
    // 星期结束
    getTeachList(page) {
      const venueId = sessionStorage.getItem('venueId')
      teacherList({ param: { venueId, status: '1' }}).then(res => {
        this.jlList = res.recordList
      })
    },
    getDetail() {
      // 获取卡类型列表
      infoCourse({ param: { courseId: this.courseId }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          const obj = res.record
          this.courseItem = obj.courseItem
          this.courseName = obj.courseName
          this.projectId = obj.courseItemIds
        })
        .catch((err) => {
          console.log(err)
        })
    },
    onSubmit() {
      const param = { ...this.param }
      // param.classNum = Number(param.classNum)
      param.courseId = this.courseId
      param.beginTime = param.time[0]
      param.endTime = param.time[1]
      const that = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          addCourseTime({
            param
          })
            .then(res => {
              if (res.errorCode === '000000') {
                that.$message.success('提交成功')
                that.$router.go(-1)
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}
</style>
